package com.globallogic.javatrainings.sergiiivanov.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import com.globallogic.javatrainings.sergiiivanov.model.Const;
import com.globallogic.javatrainings.sergiiivanov.model.University;

/**
 * Provides read/save mechanics
 * 
 * @author Sergey
 * 
 */
class DataReader {
    String fileName;

    /**
     * @return String[] - list of files by mask "*.usav"
     */
    String[] getFilesList() {
        FilenameFilter filter = new FilenameFilter() {
            @Override
            public boolean accept(File dir, String filename) {
                return filename.contains(".usav");
            }
        };
        String[] files = new File("./").list(filter);
        return files;
    }

    /**
     * Deserializes saved University instance back into entity.
     * 
     * @return deserialized {@link University}
     * @throws Exception
     *             file not found or can\'t be deserialized
     */
    University readData() throws Exception {
        University university = null;
        if (fileName != null && !Const.STRING_EMPTY.equals(fileName)) {
            ObjectInputStream in;
            in = new ObjectInputStream(new FileInputStream(fileName));
            university = (University) in.readObject();
            in.close();
        }
        return university;
    }

    /**
     * Serializes entity of Universe into file
     * 
     * @param university
     *            university for saving
     * @throws Exception
     *             file could not be saved
     */
    void saveDataToFile(University university) throws Exception {
        ObjectOutputStream out;
        out = new ObjectOutputStream(new FileOutputStream(fileName));
        out.writeObject(university);
        out.flush();
        out.close();
    }

    /**
     * Returns current file name for printing
     * 
     * @return name of current file
     */
    String getFileName() {
        if (fileName == null || Const.STRING_EMPTY.equals(fileName)) {
            fileName = "lastSave.usav";
        }
        return fileName;
    }
}
